<?php

/**
 * select_source
 * Selects the source from the config file and creates the db object
 * @param string $source
 * @return mixed $db database object
 */

function select_source($source) {
	$db = null;
	require_once('database.php');
	require_once('authorities.php');
	foreach($config as $key => $value){
		if($value['id'] == $source){
			$s = $config[$key];
			break;
		}
	}
	$d = $config[$s["database"]];
	switch( strtolower($s['dbType']) ) {
		case 'mysql':
		default:
			require_once('class.queries.mysql.php');
			$connection_string = sprintf("server=%s; database=%s; username=%s; password=%s;", $d["server"], $d["name"], $d["userName"], $d["pass"] );
			$conn = new MysqliDatabase($connection_string);
			$db = new Queries( $conn, $s["name"] );
			break;
	}

	return( $db );
}

function getSources () {
	global $authorities;
	$op = array();
	if(count($authorities)) {
		foreach($authorities as $key => $val_array) {
		$op[] = array('id' => $val_array['id'], 'name' => $val_array['name'], 'value' => $key, 'description' => $val_array['description']);
		}
	}
	return $op;
}

/**
	Calculate a precise time difference.
	@param string $start result of microtime()
	@param string $end result of microtime(); if NULL/FALSE/0/'' then it's now
	@return flat difference in seconds, calculated with minimum precision loss
*/
function microtime_diff( $start, $end=NULL ) {
	if( !$end ) {
			$end= microtime();
	}
	list($start_usec, $start_sec) = explode(" ", $start);
	list($end_usec, $end_sec) = explode(" ", $end);
	$diff_sec= intval($end_sec) - intval($start_sec);
	$diff_usec= floatval($end_usec) - floatval($start_usec);
	return floatval( $diff_sec ) + $diff_usec;
}
function getError($code) {
	$ar = array(
		  101 => 'No Command Given'
		, 102 => 'No url provided'
		, 103 => 'Remote File Could Not Be Downloaded.'
		, 104 => 'Meta File Could Not Be Extracted.'
		, 105 => 'Core File Could Not Be Extracted.'
		);
	return $ar[$code];
}
function downloadRemoteFile($url,$destinationPath) {
	if( false === ($destination=fopen($destinationPath,'w'))) return false;
	if( false === ($source=fopen($url,'r'))) return false;
	while ($a=fread($source,1024)) fwrite($destination,$a);
	fclose($source);
	fclose($destination);
	return true;
}
?>